package com.iwinding.ladygg.ui.auth;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.widget.Toast;

import com.iwinding.ladygg.R;
import com.iwinding.ladygg.constant.AuthConstants;
import com.iwinding.ladygg.utils.ToastUtil;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by hezhiyong on 2017/4/26.
 */

public class QQAuthApi {


    private QQAuthLogin mQQAuthLogin;

    private Activity mContext;
    private UserInfo mInfo;

    private Tencent mTencent;

    private static QQAuthApi INSTANCE = new QQAuthApi();

    public static QQAuthApi getInstance() {
        return INSTANCE;
    }

    public QQAuthApi() {
    }

    public void setQQAuthLogin(QQAuthLogin mQQAuthLogin) {
        this.mQQAuthLogin = mQQAuthLogin;
    }

    //初始化Context
    public void initContext(Activity mContext) {
        this.mContext = mContext;
    }

    //初始化
    public void initAuth() {
        // Tencent类是SDK的主要实现类，开发者可通过Tencent类访问腾讯开放的OpenAPI。
// 其中APP_ID是分配给第三方应用的appid，类型为String。
        mTencent = Tencent.createInstance(AuthConstants.TENCENT_APP_ID, mContext.getApplicationContext());
    }
    //设置回调
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQUEST_LOGIN ||
                requestCode == Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode,resultCode,data,listener);
        }
    }

    //登录
    public void login()
    {
        if (!mTencent.isSessionValid())
        {
            mTencent.login(mContext, "all", listener);
        }
    }

    //登出
    public void logout()
    {
        mTencent.logout(mContext);
    }

    private BaseUiListener listener = new BaseUiListener();

    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            if (null == response) {
                ToastUtil.openBaseToast(mContext, R.string.login_fail,Toast.LENGTH_SHORT);
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                ToastUtil.openBaseToast(mContext, R.string.login_fail,Toast.LENGTH_SHORT);
                return;
            }
            doComplete((JSONObject)response);
        }

        protected void doComplete(JSONObject values) {
            initOpenidAndToken(values);
            updateUserInfo();
        }

        @Override
        public void onError(UiError e) {
            Toast.makeText(mContext,
                    "Auth exception : " + e.errorMessage, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(mContext,
                    R.string.qqsdk_demo_toast_auth_canceled, Toast.LENGTH_LONG).show();
        }
    }

    public void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN);
            String openId = jsonObject.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openId)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
            }
        } catch(Exception e) {
        }
    }

    private void updateUserInfo() {
        if (mTencent != null && mTencent.isSessionValid()) {
            IUiListener listener = new IUiListener() {

                @Override
                public void onError(UiError e) {

                }

                @Override
                public void onComplete(final Object response) {
                    initUserInfo(response);
//                    Message msg = new Message();
//                    msg.obj = response;
//                    msg.what = 0;
//                    mHandler.sendMessage(msg);
//                    new Thread(){
//
//                        @Override
//                        public void run() {
//                            JSONObject json = (JSONObject)response;
//                            if(json.has("figureurl")){
//                                Bitmap bitmap = null;
//                                try {
//                                    bitmap = BitmapUtil.getbitmap(json.getString("figureurl_qq_2"));
//                                } catch (JSONException e) {
//
//                                }
//                                Message msg = new Message();
//                                msg.obj = bitmap;
//                                msg.what = 1;
//                                mHandler.sendMessage(msg);
//                            }
//                        }
//
//                    }.start();
                }

                @Override
                public void onCancel() {

                }
            };
            mInfo = new UserInfo(mContext, mTencent.getQQToken());
            mInfo.getUserInfo(listener);
        }
    }

    private void initUserInfo(Object object){
        JSONObject response = (JSONObject) object;
        String nickname = "";
        if (response.has("nickname")) {
            try {
                response.getString("nickname");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        String imgurl = "";
        if(response.has("figureurl")){
            try {
                response.getString("figureurl_qq_2");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (mQQAuthLogin!=null){
            mQQAuthLogin.onAuth(mTencent,imgurl,nickname);
        }
    }

//    Handler mHandler = new Handler() {
//
//        @Override
//        public void handleMessage(Message msg) {
//            if (msg.what == 0) {
//                JSONObject response = (JSONObject) msg.obj;
//                if (response.has("nickname")) {
//                    try {
//                        response.getString("nickname");
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//                if(response.has("figureurl")){
//                    try {
//                        response.getString("figureurl_qq_2");
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
////            else if(msg.what == 1){
////                Bitmap bitmap = (Bitmap)msg.obj;
////            }
//        }
//
//    };


    public interface QQAuthLogin {
        public void onAuth(Tencent mTencent,String imgUrl,String nickname);
    }

}
